package com.jplus.framework.aop.proxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.sf.cglib.proxy.MethodProxy;

/**
 * 代理链
 *
 * @author huangyong
 * @author yuanqy
 */
public class ProxyChain {

	private final Class<?> targetClass;
	private final Object targetObject;// 代理对象
	private final Method targetMethod;
	private final Object[] methodParams;
	private final MethodProxy methodProxy;// cglib

	private final Object originObject;// 原始对象

	private List<Proxy> proxyList = new ArrayList<Proxy>();
	private int proxyIndex = 0;

	public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy, List<Proxy> proxyList,
			Object originObject) {
		this.targetClass = targetClass;
		this.targetObject = targetObject;
		this.targetMethod = targetMethod;
		this.methodParams = methodParams;
		this.methodProxy = methodProxy;
		this.proxyList = proxyList;
		this.originObject = originObject;
	}

	public Object[] getMethodParams() {
		return methodParams;
	}

	public Class<?> getTargetClass() {
		return targetClass;
	}

	public Method getTargetMethod() {
		return targetMethod;
	}

	public Object doProxyChain() throws Throwable {
		if (proxyIndex < proxyList.size()) {
			return proxyList.get(proxyIndex++).doProxy(this);// 递归责任链
		} else {
			if (methodProxy != null)
				return methodProxy.invokeSuper(targetObject, methodParams);// Cglib代理，使用代理方法执行，完美、
			if (originObject != null)
				return targetMethod.invoke(originObject, methodParams);// jdk代理，这里会有个问题，就是被代理对象自己方法调用类中其他方法，其他方法不会被切面拦截
		}
		return null;
	}
}
